/**
 * @file   DataBusClientListModel.cpp
 * @author Djuro Drljaca (djurodrljaca@gmail.com)
 * @date   2013-05-04
 * @brief  DataBus Client List Model.
 *
 * Copyright (C) 2013  Djuro Drljaca <djurodrljaca@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "DataBusClientListModel.h"
#include "DataBusServer.h"

DataBusClientListModel::DataBusClientListModel(QObject *parent)
    : QAbstractListModel(parent),
      m_clientIdList()
{
}

int DataBusClientListModel::rowCount(const QModelIndex & /*parent*/) const
{
    return m_clientIdList.size();
}

QVariant DataBusClientListModel::data(const QModelIndex &index, int role) const
{
    if (index.isValid() == false)
    {
        return QVariant();
    }

    if (role != Qt::DisplayRole)
    {
        return QVariant();
    }

    // Return Client ID
    int row = index.row();

    if ((row < 0) ||
        (row >= m_clientIdList.size()))
    {
        return QVariant();
    }

    return m_clientIdList.at(row);
}

QVariant DataBusClientListModel::headerData(int /*section*/,
                                            Qt::Orientation /*orientation*/,
                                            int /*role*/) const
{
    return QString("");
}

void DataBusClientListModel::removeAllClients()
{
    beginRemoveRows(QModelIndex(), 0, m_clientIdList.size());

    m_clientIdList.clear();

    endRemoveRows();
}

bool DataBusClientListModel::removeClient(quint8 clientId)
{
    int index = m_clientIdList.indexOf(clientId);

    if (index < 0)
    {
        return false;
    }

    beginRemoveRows(QModelIndex(), index, index);

    m_clientIdList.removeAt(index);

    endRemoveRows();
    return true;
}

void DataBusClientListModel::addClient(quint8 clientId)
{
    int index = m_clientIdList.size();

    beginInsertRows(QModelIndex(), index, index);

    m_clientIdList.append(clientId);

    endInsertRows();
}
